const Koa = require('koa');
const Goods = require('../../models/goods/goods');
const GoodsCategory = require('../../models/goods/goods-category');
const { validateField } = require('../../helpers/validator');
const { Op } = require('sequelize');
const db = require('../../helpers/db');

/**
 * 添加商品
 * @param {Koa} ctx Koa上下文
 */
async function create(ctx) {
    const {
        categories = '',
        name = '',
        tags = '',
        cover = '',
        description = '',
        status = 0
    } = ctx.request.body;
    validateField({ categories, name, cover });
    const transaction = await db.transaction();
    try {
        const goods = await Goods.create({
            categories,
            name,
            cover,
            tags,
            description,
            status
        }, {
            transaction
        });
        const categoryList = categories.split(',').map(category => {
            return {
                category,
                goods: goods.id
            }
        });
        await GoodsCategory.bulkCreate(categoryList, {
            transaction
        });
        await transaction.commit();
        ctx.status = 201;
        ctx.body = goods;
    } catch (error) {
        await transaction.rollback();
        throw error;
    }
}

/**
 * 查询商品列表
 * @param {Koa} ctx Koa上下文
 */
async function list(ctx) {
    const {
        keywords = '',
        category = '',
        order = 'complex',
        current = 1,
        limit = 20
    } = ctx.request.query;
    const { filter = [] } = ctx.request.body;
    // 组装查询条件
    const where = {};
    // 模糊搜索
    if (keywords) {
        where.name = {
            [Op.like]: `%${keywords}%`
        }
    }
    // 筛选过滤
    if (Object.prototype.toString.call(filter) === '[object Array]') {
        filter.forEach(item => {
            const { name, type, value } = item;
            if (type === 0) {
                where[name] = value;
            } else if (type === 1) {
                where[name] = {
                    [Op.in]: value
                }
            } else if(type === 2){
                where[name] = {
                    [Op.between]: value
                }
            }
        })
    }
    // 子查询条件
    const subWhere = {};
    if (category) {
        subWhere.category = category;
    }

    // 组装排序条件
    const orderCondition = [];
    if (order === 'sales') {
        orderCondition.push(['sales', 'DESC']);
    } else if (order === 'priceAsc') {
        orderCondition.push(['price', 'ASC']);
    } else if (order === 'priceDesc') {
        orderCondition.push(['price', 'DESC']);
    }

    // 计算偏移值
    const offset = (current - 1) * limit;

    const list = await Goods.findAndCountAll({
        where,
        include: [{
            model: GoodsCategory,
            attributes: ['category'],
            on: subWhere
        }],
        order: orderCondition,
        limit: Number(limit),
        offset
    });
    ctx.status = 200;
    ctx.body = list;
}


module.exports = {
    create,
    list
}
